package com.example.servlet;

import cn.hutool.json.JSONUtil;
import com.example.entity.User;
import com.example.service.UserService;
import com.example.service.impl.UserServiceImpl;
import com.example.util.CodeUtil;
import com.example.util.HttpUtil;
import com.example.util.ResultUtil;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Objects;

@WebServlet(name = "user", value = "/user")
public class UserServlet extends HttpServlet {

    private final UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req,
                         HttpServletResponse resp)
            throws ServletException, IOException {
        String type = req.getParameter("type");
        if (type != null) {
            switch (type) {
                case "login":
                    doLogin(req, resp);
                    break;
                case "getCode":
                    doGetCode(req, resp);
                    break;
                case "verifyCode":
                    doVerifyCode(req, resp);
                    break;
                case "registry":
                    doRegistry(req, resp);
                    break;
                default:
                        break;
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req,
                          HttpServletResponse resp)
            throws ServletException, IOException {
        // 转交给doGet处理
        doGet(req, resp);
    }

    /* 处理登录 */
    private void doLogin(HttpServletRequest req,
                         HttpServletResponse resp)
            throws ServletException, IOException {
        /* 接收数据 */
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        /* 写出去 */
        /* 前端收到JSON字符串，会自动将JSON字符串解析成JS对象 */
        HttpUtil.writeJson(resp, userService.login(new User(username, password)));
    }

    /* 获取验证码 */
    private void doGetCode(HttpServletRequest req,
                           HttpServletResponse resp) throws IOException {
        // 获取一个验证码的字符串
        String code = CodeUtil.randomCode(4);
        // 获取验证码图片
        BufferedImage codeImage = CodeUtil.getCodeImage(code);
        // 验证码字符串存入会话当中
        HttpSession session = req.getSession();
        session.setAttribute("code", code);
        // 图片响应给客户端
        resp.setContentType("image/jpeg");
        ServletOutputStream os = resp.getOutputStream();
        ImageIO.write(codeImage, "jpg", os);
        os.flush();
        os.close();
    }

    /* 校验验证码 */
    private void doVerifyCode(HttpServletRequest req,
                           HttpServletResponse resp) throws IOException {
        // 前端传过来的
        String code = req.getParameter("code");
        HttpSession session = req.getSession();
        // 设置会话保持时间是60 * 5秒
        session.setMaxInactiveInterval(60 * 5);
        // 会话当中存储的，如果会话超时，这里获取到的session是一个新的会话
        // 原会话被销毁后，会话中的数据也会丢失，那这里获取的结果就是null
        Object obj = session.getAttribute("code");
        if (obj == null) {
            HttpUtil.writeJson(resp,
                    JSONUtil.toJsonStr(ResultUtil.fail("验证码已过期")));
            return;
        }
        String origin = obj.toString();
        if (Objects.equals(code, origin)) {
            HttpUtil.writeJson(resp,
                    JSONUtil.toJsonStr(ResultUtil.success()));
        } else {
            HttpUtil.writeJson(resp,
                    JSONUtil.toJsonStr(ResultUtil.fail("验证码不正确")));
        }
    }

    /* 处理注册 */
    private void doRegistry(HttpServletRequest req,
                            HttpServletResponse resp) throws IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        HttpUtil.writeJson(resp,
                userService
                        .registry(new User(username,
                                password)));
    }
}
